package com.example.login.controller;

import com.example.login.dto.*;
import com.example.login.model.User;
import com.example.login.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 判断是否为新用户接口 - 查询
     */
    @GetMapping("/check")
    public ApiResponse<Boolean> checkUser(@RequestParam String username) {
        User user = userService.getUserByUsername(username);
        return ApiResponse.success(user == null);
    }

    /**
     * 用户注册接口 - 增
     */
    @PostMapping("/register")
    public ApiResponse<User> register(@Valid @RequestBody RegisterRequest registerRequest) {
        try {
            User user = userService.register(registerRequest);
            return ApiResponse.success(user);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 账号密码登录接口 - 查
     */
    @PostMapping("/login")
    public ApiResponse<LoginResponse> login(@Valid @RequestBody LoginRequest loginRequest) {
        try {
            LoginResponse loginResponse = userService.login(loginRequest);
            return ApiResponse.success(loginResponse);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 发送短信验证码
     */
    @PostMapping("/sms/code")
    public ApiResponse<Boolean> sendSmsCode(@Valid @RequestBody SmsCodeRequest smsCodeRequest) {
        try {
            boolean result = userService.sendSmsCode(smsCodeRequest.getPhone());
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 短信验证码登录接口
     */
    @PostMapping("/login/sms")
    public ApiResponse<LoginResponse> loginBySms(@Valid @RequestBody SmsLoginRequest smsLoginRequest) {
        try {
            LoginResponse loginResponse = userService.loginBySms(smsLoginRequest);
            return ApiResponse.success(loginResponse);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
}